"use client";
import React, { useMemo, useState, useEffect } from "react";
import { Wordcloud } from "@visx/wordcloud";
import { scaleLinear } from "d3-scale";



type Props = {
    words: {
        text: string;
        en: string;
        zh?: string;
        value: number;
        fontSize: number
    }[];
};

const defaultColors = [
    "#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd",
    "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf",
    "#393b79", "#637939", "#8c6d31", "#843c39", "#7b4173"
];

export default function WordCloudFullScreen({ words }: Props) {
    const [size, setSize] = useState({
        width: 500,
        height: 400,
    });

    useEffect(() => {
        function onResize() {
            setSize({
                width: window.innerWidth,
                height: window.innerHeight,
            });
            // console.log('窗口尺寸更新:', window.innerWidth, window.innerHeight);
        }
        onResize();
        window.addEventListener("resize", onResize);
        return () => window.removeEventListener("resize", onResize);
    }, []);

    const fontScale = useMemo(() => {
        const values = words.map(w => w.value);
        return scaleLinear()
            .domain([Math.min(...values), Math.max(...values)])
            .range([20, 120]);
    }, []);

    const [tooltip, setTooltip] = useState({
        visible: false,
        text: "",
        x: 0,
        y: 0,
    });

    return (
        <div style={{ position: "relative", width: size.width, height: size.height }}>
            <svg width={size.width} height={size.height}>
                <Wordcloud
                    words={words}
                    width={size.width}
                    height={size.height}
                    font="Inter"
                    fontSize={(word) => fontScale(word.value)}
                    rotate={(d) => (d.value % 2 === 0 ? 0 : 90)}
                    padding={2}
                    spiral="archimedean"
                    random={() => 0.5}
                >
                    {(wordData: any) =>
                        wordData.map((word: any, i: number) => (
                            <text
                                key={word.en}
                                textAnchor="middle"
                                fontSize={word.fontSize}
                                fontFamily="Inter"
                                fill={defaultColors[i % defaultColors.length]}
                                transform={`translate(${word.x},${word.y}) rotate(${word.rotate})`}
                                style={{ cursor: "pointer", userSelect: "none" }}
                                onMouseOver={(e) =>
                                    setTooltip({
                                        visible: true,
                                        text: words.find((w) => w.en === word.en)?.zh || "",
                                        x: e.clientX,
                                        y: e.clientY,
                                    })
                                }
                                onMouseMove={(e) =>
                                    setTooltip((t) => ({ ...t, x: e.clientX, y: e.clientY }))
                                }
                                onMouseOut={() => setTooltip((t) => ({ ...t, visible: false }))}
                            >
                                {word.en}
                            </text>
                        ))
                    }
                </Wordcloud>
            </svg>

            {tooltip.visible && (
                <div
                    style={{
                        position: "fixed",
                        left: tooltip.x + 12,
                        top: tooltip.y + 12,
                        backgroundColor: "rgba(0,0,0,0.75)",
                        color: "#fff",
                        padding: "6px 10px",
                        borderRadius: 4,
                        pointerEvents: "none",
                        whiteSpace: "nowrap",
                        fontSize: 14,
                        zIndex: 9999,
                        userSelect: "none",
                        transition: "opacity 0.1s ease",
                    }}
                >
                    {tooltip.text}
                </div>
            )}
        </div>
    );
}
